import openai
import pandas as pd
import json
import glob
from flask import Flask, request, render_template, send_file
import os
import tempfile

API_KEY = "sk-ioSk7SbGiIu40lnOINybFdlyf2oOMbteB1dQ4jRwrhpqONtQ"
BASE_URL = "https://api.getaiai.com"
MODEL_NAME = "gpt-4o"

client = openai.Client(api_key="sk-ioSk7SbGiIu40lnOINybFdlyf2oOMbteB1dQ4jRwrhpqONtQ", base_url="https://api.getaiai.com/v1")
app = Flask(__name__)


def read_files(file_path_pattern):

    file_contents = []
    for file_path in glob.glob(file_path_pattern):
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()
            file_contents.append(content)
    return file_contents


def check_compliance(law_contents, company_contents):

    results = []
    for company_content in company_contents:
        for law_content in law_contents:
            SYSTEM_PROMPT = f"""You will behave as an expert legal advisor, proficient in Chinese law. 
You have a comprehensive understanding of the legal system in China, with extensive academic qualifications, including a PhD in law. 
Your primary role is to provide expert legal advice, drawing on your deep knowledge of Chinese legislation, regulations, and legal precedents. 
You can proficiently quote Chinese laws to support your arguments and provide relevant real-life examples from within China for both prosecution and defense scenarios. 
It is essential that your legal advice be professional and accurate, as you play a crucial role in informing and guiding users about legal matters within the Chinese context. 
You must communicate exclusively in Chinese, ensuring that your responses are tailored to the linguistic and cultural nuances of the Chinese legal system.

            你将使用中文回答用户的问题，除非用户使用的是其他语言。
            下面用户将提供相关法律法规片段和公司的文件，你将参考用户提供的法律法规片段和其他任何可能相关的中国法律，检查这些文件并返回不符合法规的内容
            你将回复JSON格式字符串，JSON定义如下：
            {{ "result" : [{{"content":"<公司文件片段>", "law":"违反《中华人民共和国XXX法》第<>条、第<>条"}}]}}
            result: 检查的结果list
            content: 不符合法规的内容部分，尽可能精简
            law: 违反的法律法规，尽可能精简
            你将输出完整的plain json字符串，不包括markdown格式等其他内容。

            法律片段如下：
            {law_content}

            公司文件如下：
            {company_content}
            """
            USER_MESSAGE = ""
            completion = client.chat.completions.create(
                model=MODEL_NAME,
                messages=[
                    {"role": "system", "content": SYSTEM_PROMPT},
                    {"role": "user", "content": USER_MESSAGE},
                ],
                response_format={"type": "json_object"},
            )
            try:
                response_json = json.loads(completion.choices[0].message.content)
                results.extend(response_json.get("result", []))
            except json.JSONDecodeError:
                print(f"解析结果出现错误，返回内容为：{completion.choices[0].message.content}")
    return results


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':

        if 'law_files' not in request.files or 'company_files' not in request.files:
            return "请上传法律法规文件和公司文件", 400

        law_files = request.files.getlist('law_files')
        company_files = request.files.getlist('company_files')


        with tempfile.TemporaryDirectory() as temp_dir:
            law_file_paths = []
            company_file_paths = []

            # 保存法律法规文件到临时文件夹并记录路径
            for file in law_files:
                file_path = os.path.join(temp_dir, file.filename)
                file.save(file_path)
                law_file_paths.append(file_path)

            # 保存公司文件到临时文件夹并记录路径
            for file in company_files:
                file_path = os.path.join(temp_dir, file.filename)
                file.save(file_path)
                company_file_paths.append(file_path)

            # 读取临时文件夹中的法律法规文件内容
            law_contents = read_files(os.path.join(temp_dir, '*'))

            # 读取临时文件夹中的公司文件内容
            company_contents = read_files(os.path.join(temp_dir, '*'))

            compliance_results = check_compliance(law_contents, company_contents)

            # 将结果整理成DataFrame，准备写入Excel
            data = []
            for item in compliance_results:
                data.append({
                    "content": item.get("content", ""),
                    "law": item.get("law", "")
                })
            df = pd.DataFrame(data)

            # 创建临时Excel文件保存结果
            with tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False) as tmp_excel:
                df.to_excel(tmp_excel.name, index=False)

            # 渲染结果页面并传递数据，这里添加 tmp_excel.name 作为参数传递给模板
            return render_template('result.html', results=compliance_results, file_path=tmp_excel.name)

    return render_template('index.html')


@app.route('/download', methods=['GET'])
def download():
    # 获取临时Excel文件路径并返回下载
    file_path = request.args.get('file_path')
    return send_file(file_path, as_attachment=True, download_name='results.xlsx')


if __name__ == '__main__':
    app.run(debug=True)